#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Provides Routes integration."""

# http://docs.python.org/whatsnew/pep-328.html
from __future__ import absolute_import
from __future__ import print_function   # deletes the print statement
#from __future__ import unicode_literals # unicode by default

from routes import url_for as _url_for
from cherrypy import request, HTTPRedirect, url as _cherry_url, \
                     dispatch as _dispatch

"""
def url(*args, **k):
    Combines cherrypy.url() with routes.url_for().
    routes' url_for() is called, then the result goes through
    cherrypy.url() in order to put it in the right prefix.
    
    Inspired by http://tools.cherrypy.org/wiki/RoutesUrlGeneration
    
    url = _url_for(*args, **k)
    if url is None:
        raise RuntimeError("No url for: " + repr(args) + " / " + repr(k))
    return _cherry_url(url)
"""
# The above url() function turns out not to help much...
url = _url_for

def redirect(*a, **kw):
    "Redirects to some route. The syntax is the same as routes' url_for()."
    status = kw.pop('status', 303)
    raise HTTPRedirect(url(*a, **kw), status=status)

def install_url_and_redirect(app):
    import webpyte
    webpyte.redirect = redirect  # Make the redirect() function available...
    webpyte.url = url            # ...directly from webpyte. url() also...
    app.defaultdict["url"] = url # ... can be called from templates.
